using Godot;
using System;

public partial class Main : Node
{

    [Export]
    public PackedScene MobScene { get; set; }

    private int _score;

    // 背景音乐
    AudioStreamPlayer musicAudio = null;
    // 死亡音乐
    AudioStreamPlayer deathSoundAudio = null;

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        // NewGame();
        musicAudio = this.GetNode<AudioStreamPlayer>("Music");
        deathSoundAudio = this.GetNode<AudioStreamPlayer>("DeathSound");
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {

    }

    // 游戏结束
    public void GameOver()
    {
        this.GetNode<Timer>("MobTimer").Stop();
        this.GetNode<Timer>("ScoreTimer").Stop();

        // 角色失败显示文案
        HUD hUD = this.GetNode<HUD>("HUD");
        hUD.ShowGameOver();

        // 暂停背景音乐
        musicAudio.Stop();
        // 播放死亡音乐
        deathSoundAudio.Play();
    }

    // 开始游戏
    public void NewGame()
    {
        _score = 0;
        Area2D player = this.GetNode<Area2D>("Player");
        Marker2D startPosition = this.GetNode<Marker2D>("StartPosition");
        player.Position = startPosition.Position;

        Timer startTimer = this.GetNode<Timer>("StartTimer");
        startTimer.Start();

        HUD hUD = this.GetNode<HUD>("HUD");
        hUD.UpdateScore(_score);
        hUD.ShowMassge("Get Ready!");
        // 清除敌人
        this.GetTree().CallGroup("mobs", Node.MethodName.QueueFree);
        player.Show();
        player.GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred(CollisionShape2D.PropertyName.Disabled, false);

        // 播放背景音乐
        musicAudio.Play();
    }

    // 控制怪物产生
    private void OnMobTimerTimeout()
    {
        // 创建敌人实例
        Mob mob = MobScene.Instantiate<Mob>();

        // 创建在PathFollow2D随机的一个位置
        PathFollow2D mobSpawnLocation = this.GetNode<PathFollow2D>("Path2D/MobSpawnLocation");
        mobSpawnLocation.ProgressRatio = GD.Randf();

        mob.Position = mobSpawnLocation.Position;

        // 设置敌人的方向垂直于路径方向
        float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;

        // 为方向添加一些随机性
        direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
        mob.Rotation = direction;

        // 速度
        Vector2 velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
        mob.LinearVelocity = velocity.Rotated(direction);

        // 生成子级元素
        AddChild(mob);
    }
    // 开始计算分数
    private void OnScoreTimerTimeout()
    {
        _score++;
        // 文案同步
        this.GetNode<HUD>("HUD").UpdateScore(_score);
    }

    /***
     * 启动定时
     * one shot = true 此定时器只会触发一次
     */
    private void OnStartTimerTimeout()
    {
        this.GetNode<Timer>("MobTimer").Start();
        this.GetNode<Timer>("ScoreTimer").Start();
        // GD.Print("日志调试");

    }



}
